
export default class GameEvent {
    private static events: Map<string, Map<cc.Component, Function>> = new Map();

    // 注册事件，使用具体的类型代替Function
    public static register(ower: cc.Component, type: string, cb: Function) {
        let typeEvents = this.events.get(type) || new Map();
        if (!typeEvents.has(ower)) {
            typeEvents.set(ower, cb);
            this.events.set(type, typeEvents);
        } else {
            typeEvents.set(ower, cb);
        }
    }

    // 根据事件类型删除事件
    public static unregister_with_type(type: string) {
        this.events.delete(type);
    }

    // 删除节点下所有事件
    public static unregister_with_ower(ower: cc.Component) {
        this.events.forEach((typeEvents, type) => {
            typeEvents.delete(ower);
            if (typeEvents.size === 0) {
                this.events.delete(type);
            }
        });
    }

    // 发送事件，添加异常处理
    public static dispatch(type: string, data: any = null) {
        let typeEvents = this.events.get(type);
        if (!typeEvents) {
            console.log("GameEvent.dispatch 没找到事件 ======> " + type);
            return;
        }

        ////////////////////获得 typeEvents中所有key , 验证key组件是否有效 , 然后执行回调
        let keys = Array.from(typeEvents.keys());
        for (let i = 0; i < keys.length; i++) {
            if (cc.isValid(keys[i].node)) {
                let callback = typeEvents.get(keys[i]);
                if (callback) {
                    callback(data);
                }
            }
        }

    }
}
